package xxx;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class runSql{ //数据库操作方法封装
	
	
	public  int update(Connection con,String sql){ // 调用此方法执行一切 ‘增，删，改’ 相关的SQL语句
		try {
			Statement s = con.createStatement();
			return s.executeUpdate(sql);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return -1;
		}
	}
	
	public  String select(Connection con,String sql){ //调用此方法执行一切 ‘查’ 相关的SQL语句
		ResultSet rs = null;
		String res = "";
		try {
			Statement s = con.createStatement();
			rs = s.executeQuery(sql);
			res = getRes(rs);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return "ERROR";
		}
		return res;
	}
	
	private  String getRes(ResultSet rs){ //此方法为查询返回其结果集中的内容，返回值为按行按列均由标记的字符串。
		String res = "";
		try
		{
			ResultSetMetaData d = rs.getMetaData();
			int cols = d.getColumnCount();
			while(rs.next()){
				for(int i=0;i<cols;i++){
					res = res+rs.getString(i+1)+"\u0005";
				}
				res+="\u0006";
			}
		}
		catch(Exception e){
			res = res +"\n"+e.getMessage();
			System.out.println(e.getMessage());
		}
		return res;
	}
}